package com.cn.algorithm.two.line.test;

import java.util.Arrays;

public class MergeSortJ {

    public static void main(String[] args) {
        int[] arr = {9, 7, 4, 2, 5, 3, 8};
        int[] sort = sort(arr);
        System.out.println(Arrays.toString(sort));
    }
    public static int[] sort(int[] arr) {
        if (arr == null || arr.length <= 1) {
            return arr;
        }
        int mid = arr.length >> 1;
        int[] left = Arrays.copyOfRange(arr, 0, mid);
        int[] right = Arrays.copyOfRange(arr, mid, arr.length);
        return merge(sort(left), sort(right));
    }

    public static int[] merge(int[] left, int[] right) {
        int i = 0;
        int j = 0;
        int k = 0;
        int[] tmp = new int[left.length + right.length];
        while (i < left.length && j < right.length) {
            if (left[i] < right[j]) {
                tmp[k++] = left[i++];
            }else {
                tmp[k++] = right[j++];
            }
        }
        while (i < left.length) {
            tmp[k++] = left[i++];
        }
        while (j < right.length) {
            tmp[k++] = right[j++];
        }
        return tmp;
    }
}
